import * as CryptoJS from 'crypto-js';
const createChunk = (file, index, chunkSize) => {
    return new Promise((resolve, reject) => {
        let start = index * chunkSize;
        let end = Math.min(start + chunkSize, file.size);  // Ensure end is within file size
        let blob = new Blob([file.slice(start, end)],{type:file.type});

        // Read Blob as ArrayBuffer
        const reader = new FileReader();

        reader.onload = function(event) {
            // Create WordArray from ArrayBuffer
            const wordArray = CryptoJS.lib.WordArray.create(event.target.result);
            // Compute SHA256 hash
            const hash = CryptoJS.SHA256(wordArray).toString(CryptoJS.enc.Hex);

            resolve({
                blob: blob,
                start,
                end,
                index: index + 1,
                name: file.name,
                hash: hash
            });
        };

        reader.onerror = function(error) {
            reject(error);
        };

        reader.readAsArrayBuffer(blob);  // Read Blob as ArrayBuffer
    });
};

onmessage = async (e)=>{
    let {
        file,
        CHUNK_SIZE,
        startChunkIndex,
        endChunkIndex
    } = e.data
    let promises = []
    for (let i = startChunkIndex; i < endChunkIndex; i++) {
        promises.push(createChunk(file, i, CHUNK_SIZE))
    }
    let chunks = await Promise.all(promises)
    postMessage(chunks)

}
